/*
 * On my machine atomic integer works approx 4 times faster!
 */

import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerWithLock {
	private int val = 0;

	// try not synchronized - runs much faster and produces wrong results :)
	synchronized void increment() {
		val++;
	}

	void benchmark(Thread t1, Thread t2) throws InterruptedException {
		long timeBefore = Calendar.getInstance().getTimeInMillis();

		t1.start();
		t2.start();

		t1.join();
		t2.join();

		long timeAfter = Calendar.getInstance().getTimeInMillis();

		System.out.println("Milliseconds elapsed: " + (timeAfter - timeBefore));
	}

	public static void main(String[] args) throws InterruptedException {
		final int count = 10000000;

		AtomicIntegerWithLock myint = new AtomicIntegerWithLock();
		Thread t1 = new SynchronizedThreadIncrementer(myint, count);
		Thread t2 = new SynchronizedThreadIncrementer(myint, count);
		myint.benchmark(t1, t2);
		System.out.println("Final value: " + myint.val);

		AtomicInteger myint2 = new AtomicInteger();
		Thread t3 = new AtomicThreadIncrementer(myint2, count);
		Thread t4 = new AtomicThreadIncrementer(myint2, count);
		myint.benchmark(t3, t4);
		System.out.println("Final value: " + myint2.intValue());
	}

}
